#include <Arduino.h>
#include "application.h"
#include "pwifi.h"
#include "ptime.h"
#include "web_server.h"
#include "plog.h"
#include "persistence.h"
#include "my_u8g2.h"

static ModeType switch_modes[] = {
    MODE_RAW_DATA,
#ifndef U8G2_SLEEP_ENABLE
    MODE_GS_EC02,
    MODE_GS_TVOC,
    MODE_ES_TEMP,
// MODE_ES_HUMI,
// MODE_ES_PRES,
#endif
};
static uint32_t mode_sw_idx = 0;
static ModeType mode_now = MODE_RAW_DATA;
static ModeType mode_last = MODE_RAW_DATA;

void App_mode_loop(Sensor_result_t *data)
{
  bool graph_reset = false;
  if (mode_last != mode_now)
  {
    LOG_INFO("App mode switch, mode_last: %d, mode_now: %d", mode_last, mode_now);
    graph_reset = true;

    if (mode_last == MODE_WEB_SERVER)
    {
      web_server_stop();
    }
  }

  ModeType mode_last_tmp = mode_now;
  switch (mode_now)
  {
  case MODE_RAW_DATA:
    App_mode_raw_data(data);
    break;
  case MODE_GS_EC02:
    App_mode_gs_ec02(data, graph_reset);
    break;
  case MODE_GS_TVOC:
    App_mode_gs_tvoc(data, graph_reset);
    break;
  case MODE_ES_TEMP:
    App_mode_es_temp(data, graph_reset);
    break;
  case MODE_ES_HUMI:
    App_mode_es_humi(data, graph_reset);
    break;
  case MODE_ES_PRES:
    App_mode_es_pres(data, graph_reset);
    break;
#ifndef WEB_SERVER_DEFAULT_ON
  case MODE_WEB_SERVER:
    web_server_start();
    U8G2_web_server_started(WIFI_AP_MODE_SSID, WIFI_AP_MODE_PASSWORD, WiFi.localIP().toString().c_str());
    break;
#endif
  case MODE_SYS_CONFIG:
    App_init_sys_config();
    mode_now = mode_last; // 只进来一次
    mode_last_tmp = MODE_SYS_CONFIG;
    break;
  default:
    break;
  }
  mode_last = mode_last_tmp;
}

void App_mode_next()
{
  mode_sw_idx++;
  if (mode_sw_idx >= (sizeof(switch_modes) / sizeof(switch_modes[0])))
  {
    mode_sw_idx = 0;
  }
  mode_now = switch_modes[mode_sw_idx];
}

void App_mode_set(ModeType mode)
{
  mode_now = mode;
}

void App_init_sys_config()
{
  pwifi_sta_mode_init();
  // 连上wifi后要做的事情
  U8G2_message("init sys config");
  sync_sys_time();
  sync_sys_time_to_ds1302();

  // 关闭sta模式
  pwifi_sta_close();

  delay(1000);
}

// todo将来还可以将nvs flash中存的上次同步时间和当前时间做对比，超过一定时间就强制同步
bool need_init_sys_config(void)
{
  // 简单判断是否有采集数据
  uint32_t file_cnt = P_LittleFS.getFileCounts();
  return file_cnt == 0;
}

void App_mode_raw_data(Sensor_result_t *res)
{
  U8G2_sensor_raw_data(res);
}

void App_mode_gs_ec02(Sensor_result_t *res, bool reset)
{
  U8G2_gas_sensor_eco2_graph(res->gs.eco2, reset);
}

void App_mode_gs_tvoc(Sensor_result_t *res, bool reset)
{
  U8G2_gas_sensor_tvoc_graph(res->gs.tvoc, reset);
}

void App_mode_es_temp(Sensor_result_t *res, bool reset)
{
  U8G2_env_sensor_temp_graph(res->es.temperature, reset);
}

void App_mode_es_humi(Sensor_result_t *res, bool reset)
{
}

void App_mode_es_pres(Sensor_result_t *res, bool reset)
{
}

void App_sensor_persistent(Sensor_result_t *data)
{
  Timestamp_t ts = timestamp_from_ds1302();

  P_LittleFS.writeData(ts, &(data->gs), &(data->es));
}
